<!--发布作品-->
<template>
  <el-drawer
    size="600px"
    :title="detailInfo.taskName"
    :visible="visible"
    @close="updateVisible(false)">
    <el-form
      ref="form"
      class="btn-padding"
      :show-message="false"
      :model="form"
      :rules="rules"
      label-width="90px"
      @keyup.enter.native="submit"
      @submit.native.prevent>
      <div class="flex-align-center">
        <div v-for="(i,j) in channelList" :key="j" @click="channelClick(j)">
          <div :class="channelIndex == j ? 'sel-title-class' : 'title-class'" class="default" >{{i.name}}</div>
        </div>
      </div>

      <el-card shadow="never">
        <div class="fit-title">选择文案</div>
        <el-row :gutter="15" class="flex-wrap">
          <el-col :span="24">
            <el-form-item label="SEO文案" prop="seoCopywriting"
                          :rules="!form.seoCopywriting  ? { required: true, message: '请选择文案', trigger: ['blur','change']} : {required: false}">
              <!--SEO文案-->
              <div style="width: 66%;">
                <acties ref="seoActies" :lists="seoList" @getData="selectCopy"></acties>
              </div>
            </el-form-item>
          </el-col>
          <!--<el-col :span="24" v-if="channelIndex==0">
            <el-form-item label="@用户" prop="aite">
              <div style="width: 66%;">
                <userPage ref="user" :lists="userList" @getData="selUser"></userPage>
              </div>
            </el-form-item>
          </el-col>-->
        </el-row>

        <div class="fit-title m-top30">渠道与挂载</div>
        <el-form-item label="发布设置" prop="shareToPublish"  v-if="form.releaseChannel==1">
          <el-radio-group v-model="form.shareToPublish">
            <el-radio :label="1">跳转到发布页（减少用户操作）</el-radio>
            <el-radio :label="0">跳转到剪辑页</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--form.releaseChannel 发布渠道：（1.D音2.小程序3.K手）-->
        <!--        D音-->
        <div v-if="form.releaseChannel==1" class="check-star">
          <el-form-item label="挂载类型" prop="mountType">
            <el-radio-group v-model="form.mountType" @input="clear">
              <el-radio :label="1">商家POI</el-radio>
              <el-radio :label="2">小程序</el-radio>
              <el-radio :label="3">不挂载</el-radio>
            </el-radio-group>
          </el-form-item>


          <el-row :gutter="15" class="flex-wrap no-check-star">
            <!--小程序-->
            <el-col :span="24" v-if="form.mountType==2 ">
              <!--非h5传anchorUrl(挂载小程序地址)，否则传全部-->
              <el-form-item label="小程序地址" prop="appUrl">
                <el-input
                  @input="onInput"
                  style="width: 66%;"
                  class="in-append"
                  type="text"
                  v-model="form.appUrl"
                  placeholder="请输入小程序地址"
                  clearable>
                </el-input>
              </el-form-item>
              <!--接口需加字段 start-->
              <el-form-item label="小程序标题" prop="appTitle">
                <el-input
                  @input="onInput"
                  style="width: 66%;"
                  class="in-append"
                  type="text"
                  v-model="form.appTitle"
                  placeholder="请输入小程序标题"
                  clearable>
                </el-input>
              </el-form-item>
              <el-form-item label="小程序id" prop="appId" class="delInput">
                <el-input
                  @input="onInput"
                  style="width: 66%;"
                  class="in-append"
                  type="text"
                  v-model="form.appId"
                  max="20"
                  placeholder="请输入小程序id"
                  clearable>
                </el-input>
              </el-form-item>
              <!--end-->
            </el-col>
            <!--商家POI-->
            <el-col :span="24" v-if="form.mountType==1">
              <el-form-item label="城市" prop="city">
                <!-- type="provinceCity" 增加type 是省市选择，不加，默认省市区选择-->
                <!-- placeholder：报错需修改-->
                <regions-select
                  @input="selectCity"
                  :placeholder="provinceCity ?provinceCity :'请选择省市'"
                  style="width: 66% !important;"
                  v-model="provinceCity"
                  type="provinceCity"
                  class="ele-fluid"
                />
              </el-form-item>
              <el-form-item label="商家简称" prop="merchantAbbreviation">
                <el-input
                  @input="referred"
                  style="width: 66%;"
                  class="in-append"
                  type="text"
                  v-model="form.merchantAbbreviation"
                  placeholder="请输入商家简称"
                  clearable>
                  <el-button slot="append" icon="el-icon-search" @click="seachPoi" :loading="poiLoading"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="POI地址" prop="poiName">
                <el-select
                  style="width: 66%;"
                  v-model="form.poiName"
                  placeholder="请输入城市和商家简称搜索可加载"
                  class="ele-block"
                  clearable
                  @change="addressPoi"
                >
                  <div v-for="(i,j) in poiList" :key="j">
                    <el-option style="min-width:300px;max-width: 600px;" :label="i.poi_name" :value="i" />
                  </div>
                  <el-button type="text" style="padding:10px 20px ;color: #409EFF" @click="lookMore()" :loading="poiLoading" v-if="nextStep!=-1">查看更多</el-button>
                  <div v-else class="m-out">已经到底了~</div>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 视频号-->
        <el-row :gutter="15" v-if="form.releaseChannel==3">
          <el-form-item label="挂载类型" prop="sphMountType" class="check-star">
            <el-radio-group v-model="form.sphMountType">
              <el-radio :label="1">公众号文章</el-radio>
              <el-radio :label="3">不挂载</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-col :span="24" class="no-check-star" v-if="form.sphMountType==1">
            <el-form-item label="链接" prop="sphLink">
              <el-input
                class="in-append"
                type="text"
                style="width: 66%;"
                v-model="form.sphLink"
                placeholder="请输入链接地址"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        K手-->
        <el-row :gutter="15" v-if="form.releaseChannel==2">
          <el-col :span="24">
            <el-form-item label="挂载小黄车" prop="littleYellowCarId">
              <el-input
                style="width: 66%;"
                class="in-append delInput"
                type="number"
                oninput="value=value.replace(/[^0-9]/g,'')"
                v-model.number="form.littleYellowCarId"
                placeholder="请输入需要挂载小黄车的商品ID"
                clearable>
              </el-input>
              <el-link type="primary" style="margin-left: 17px;">如何获取商品ID<i class="el-icon-question"></i> </el-link>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <div class="flex-end btn-absolute" >
      <el-button round @click="resetting">取消</el-button>
      <el-button type="primary" class="margin20" round  @click="confirm()" :loading="loading">去授权发布</el-button>
    </div>
    <!-- 视频号发布授权二维码-->
    <scan-code ref="codeDialog" @success="codeSussess"></scan-code>
    <!--  D音 ‘静态’授权二维码-->
    <static-code ref="staticDialog" :type="20"></static-code>
  </el-drawer>
</template>

<script>
  import staticCode from "/src/views/matrixManage/accountManage/accountList/components/static-code";
  import acties from "@/components/pagination/activities";
  import userPage from '@/components/pagination/user-page'
  import scanCode from '@/views/matrixManage/releaseManage/videoId/code-img'

  import {projectPage} from "@/api/creatCenter/authoringClips";
  import {querySeo} from "@/api/matrixManage/seo";
  import {getKsCode,getDyH5Code,finishTask,sphIssue} from "@/api/digitalHumanManagement/taskList";

  import {dyPoi} from "@/api/releaseManage/tiktok";
  import RegionsSelect from "@/views/explosiveCode/releaseActivity/components/city-select";
  import {accreditPage} from "@/api/explosiveCode/follow";
  import {accountCode, accountCookie, accountH5} from "@/api/matrixManage/accountList";
  import {publishCreateVideo, publishVideo} from "@/api/releaseManage/videoId";
  export default {
    components:{RegionsSelect,acties,userPage,scanCode,staticCode},
    name: "publish-works",
    props:{
      visible:Boolean
    },
    data()
    {
      // 默认表单数据
      const defaultWhere = {
        merchantId: this.$store.state.user.info.merchantId,  // 商户id
        // videoMaterialId: '',
        taskId:0,
        // 发布渠道
        releaseChannel:1,
        // 挂载类型
        mountType:1,
        // 视频号——公众号文章 挂载
        sphMountType:1,
        shareToPublish:1, //发布设置 必填
      };
      return {
        rules: {
          seoCopywriting: [
            {
              required: true,
              message: '请选择SEO文案',
              trigger: 'blur'
            }
          ],
          /*aite: [
            {
              required: true,
              message: '请选择@用户',
              trigger: 'blur'
            }
          ],*/

          //poi
          poiName: [
            {
              required: true,
              message: '请选择POI地址',
              trigger: 'blur'
            }
          ],

          //小程序
          anchorUrl: [
            {
              required: true,
              message: '请输入小程序地址',
              trigger: 'blur'
            }
          ],
          anchorTitle: [
            {
              required: true,
              message: '请输入小程序标题',
              trigger: 'blur'
            }
          ],
          anchorId: [
            {
              required: true,
              message: '请输入小程序id',
              trigger: 'blur'
            }
          ],

          sphLink: [
            {
              required: true,
              message: '请输入链接地址',
              trigger: 'blur'
            }
          ],
          //橱窗商品
          /*promotionLink: [
            {
              required: true,
              message: '请输入商品地址',
              trigger: 'blur'
            }
          ],
          elasticTitle: [
            {
              required: true,
              message: '请输入橱窗商品短标题',
              trigger: 'blur'
            }
          ],*/
        },
        userList:[], // @用户list
        dataForm:{
          types:1,  // types：1用户库 2关注我
          merchantId: this.$store.state.user.info.merchantId,
          limit:10,
          page:1,
        },
        seoInfo:{
          username:this.$store.state.user.info.username,
          limit:10,
          page:1,
          // seo 所属平台：1D音2K手3视频号
          platform:1
        },
        nextStep:'0',   // 是否有 “游标第一页”
        // 回显值
        initValue: undefined,
        poiLoading:false,
        loading:false,
        // 省市
        provinceCity:'',
        // POI地址
        poiList:[],
        list: [],
        // seo 列表
        seoList:[],
        // 发布渠道
        channelIndex:0,
        channelList:[
          {
            name:'D音',
            id:1,
          },
          {
            name:'K手',
            id:2,
          },
          {
            name:'视频号',
            id:3,
          },
        ],
        defaultWhere,
        form:{ ...defaultWhere },
        detailInfo:{},
        // 发布任务id
        releaseId:null
      }
    },
    activated() {
      console.log("路由切换activated=====")
      console.log('created11111111111111111', this.form)
    },
    mounted(){
    },
    methods:{
      onInput(e){
        // forceUpdate用来强制渲染，避免data中对象层次太深，Vue框架不自动渲染的情况。
        this.$forceUpdate();
        console.log("输入框inputeeeeee",e)
      },
      show(row,taskId){
        console.log("show=========",row)
        this.detailInfo=row
        // taskId==0 代表是数字人——成品发布进入。需要传id（productId）和任务id（taskId）
        if(taskId==0){
          this.form.taskId=row.taskId
          this.form.productId=row.id
        }
        else{
          this.form.taskId=taskId
        }
        this.seoInit()
        // this.userInit()
      },

      // 视频号扫描成功返回（子组件）
      codeSussess(e){
        let parms={
          cookie:e,
          releaseId:this.releaseId
        }
        if(parms.cookie){
          this.publishVideo(parms)
        }
        else{
          this.$message.error("未获取到扫码信息，请重试！")
        }
      },
      publishVideo(parms){
        console.log("parms========",parms)
        sphIssue(parms)
          .then((data) => {
            console.log("视频号提交成功", data)
            this.updateVisible(false)
            this.$message.success('发布成功！')
          })
          .catch((e) => {
            this.loading=false
            this.$message.error(e);
          });
      },

      // 查询用户库
      userInit(){
        accreditPage(this.dataForm)
          .then((data) => {
            console.log("查询用户库data",data,'this.$refs[\'user\']',this.$refs['user'])
            this.userList=data.list;
            this.$nextTick(()=>{
              this.$refs['user'].init()
            })
          })
          .catch((e) => {
            this.$message.error(e);
          });
      },
      // 发布渠道
      channelClick(e){
        this.channelIndex=e
        // this.form.releaseChannel=this.channelList[e].typeId
        this.form.releaseChannel=this.channelList[e].id
        // seo 所属平台：1D音2K手3视频号
        this.seoInfo.platform=this.form.releaseChannel  // 需修改（seo所属平台id 和channelList，id 对应不上
        this.seoInit()
      },

      // 获取“seo文案”
      selectCopy(e){
        console.log('选择文案',e)
        this.form.seoCopywritingId=e.id //SEO ID
        this.$set(this.form,'seoCopywriting',e.taticsName)  //SEO名称
        // this.form.seoCopywriting=e.taticsName //SEO名称
        console.log('this.form=======',this.form)
      },

      // 选择用户
      selUser(e){
        console.log('选择用户=====',e)
        this.form.aite= e.id,
          this.form.aiteNickname= e.nickname
      },

      clear(){
        if(this.form.mountType==2){
          this.form.merchantAbbreviation = ''
          this.form.poiName = ''
          this.form.cityName = ''
          this.form.city = ''
          this.provinceCity=''
        }
        if(this.form.mountType==1){
          this.form.appUrl = ''
          this.form.appTitle = ''
          this.form.appId = ''
        }
        if(this.form.mountType==3){
          this.form.merchantAbbreviation = ''
          this.form.poiName = ''
          this.form.cityName = ''
          this.form.city = ''
          this.provinceCity=''

          this.form.appUrl = ''
          this.form.appTitle = ''
          this.form.appId = ''
        }
        console.log("this.form",this.form)
      },

      seoInit(){
        if(this.form.seoCopywriting){
          delete this.form.seoCopywritingId
          this.$set(this.form,'seoCopywriting','')  //SEO名称
          delete this.form.seoCopywriting
          this.$refs['seoActies'].clear()
        }
        this.querySeoList()
      },
      querySeoList(){
        // 查询SEO文案【分页查询】 在查询列表页使用
        querySeo(this.seoInfo)
          .then((data) => {
            console.log('seoInit==========data.',data,'this.$refs[\'seoActies\']',this.$refs['seoActies'])
            this.seoList=data.list
            this.$nextTick(()=>{
              this.$refs['seoActies'].init()
            })
          })
          .catch((e) => {
            console.log("进入catch111111======",e)
            this.$message.error(e.msg);
          });
      },
      //搜索poi地址(下一页需要传入‘游标’字段，注意修改
      seachPoi(){
        // 商家地址选择this.provinceCity[1].value,  0:省 1：市
        console.log("商家地址this.provinceCity=======",this.provinceCity,'商家简称merchantName',this.form.merchantAbbreviation)
        if(!this.provinceCity){
          this.$message.warning("请选择省市")
          return
        }
        if(!this.form.merchantAbbreviation){
          this.$message.warning("请输入商家简称")
          return
        }
        this.poiLoading=true
        this.nextStep='0' // 重新搜索则游标归0
        // if(!this.form.city){
        console.log("this.provinceCity",this.provinceCity)
        this.form.city=this.provinceCity[1].value  // 该参数 为传值（city）
        this.form.cityName=this.provinceCity[0].label+'/'+this.provinceCity[1].label
        // }
        console.log("poi查询===",this.form)
        this.datasource(this.nextStep,10)
      },
      datasource(page, limit) {
        dyPoi(this.form.merchantAbbreviation,this.form.city,page, limit)
          .then((data) => {
            this.poiLoading=false
            console.log("this.nextStep", this.nextStep)
            if(this.nextStep==0){
              this.poiList=data.data.pois ? data.data.pois : []
              if(this.poiList.length<=0){
                return
              }
              this.form.poiName= this.poiList[0].poi_name // 赋值poi地址
              this.form.poiId= this.poiList[0].poi_id  //POI ID
              console.log('设置poiName1111111111111')
            }
            else{
              if(data.data.pois){
                this.poiList= [...this.poiList,...data.data.pois]
              }
            }
            /*has_more:是否有下一页
            cursor:游标第一页为0，后续页游标在响应数据中获取*/
            this.nextStep=data.data.has_more==false ? -1 : data.data.cursor
          })
          .catch((e) => {
            this.poiLoading=false
            this.$message.error(e);
          });


      },
      // 查看更多
      lookMore(){
        this.poiLoading=true
        this.datasource(this.nextStep,10)
      },
      // 城市选择
      selectCity(e){
        console.log("城市选择e=====",e)
        console.log("provinceCity",this.provinceCity,this.form)
        this.clearPoi(1)
      },
      // 商家简称输入
      referred(e){
        console.log("商家简称输入=====",e)
        this.clearPoi(2)
      },
      // 清空POI地址
      clearPoi(type){
        // type 1:城市 2:商家简称
        if(this.form.poiId && type==1){  // 清空poi地址文本并清空poiId
          delete this.form.poiId
          if(this.provinceCity.length<=0){
            this.provinceCity='' // 清除城市文本，在搜索前提示
          }
          this.$set(this.form,'poiName','')
        }
        this.poiList=[]
        if(this.form.poiName){
          this.$message.warning("请重新搜索")
        }
        delete this.form.poiName // 清空poi地址文本 和poi地址list
      },
      // POI地址
      addressPoi(e){
        this.form.poiId=e.poi_id  //POI ID
        this.$delete(this.form, 'poiName')
        this.$set(this.form,'poiName',e.poi_name) //POI 名称
        console.log("POI地址e-------",e,'this.form',this.form,this.form.poiName)
      },
      resetting(){
        this.updateVisible(false)
      },
      confirm(){
        console.log("this.form=====",this.form)
        this.$refs.form.validate((valid, obj) => {
          console.log('valid',valid,'obj',obj)
          for(let i in obj){
            console.log("i",i)
            console.log("obj=========",obj[i][0].message)
            this.hint=obj[i][0].message
            break
          }
          console.log('this.hint',this.hint)
          if (valid) {
            if(this.form.releaseChannel!=1){
              delete this.form.shareToPublish
            }
            console.log("成功")
            this.loading=true
            // form.releaseChannel  ：1_D音  2_K手 3_视频号
            // form.mountType  ：1_商家POI  2_小程序 3_不挂载
            if(this.form.releaseChannel==1){
              this.wananchiClear()
              if(this.form.mountType==1){
                this.appletClear()
              }
              if(this.form.mountType==2){
                this.poiClear()
              }
              if(this.form.mountType==3){
                this.appletClear()
                this.poiClear()
              }
            }
            if(this.form.releaseChannel==3){
              this.appletClear()
              this.poiClear()
            }
            if(this.form.releaseChannel==2){
              this.appletClear()
              this.poiClear()
              this.wananchiClear()
            }
            this.save()
          } else {
            console.log("进入非空提示",valid,'22',this.form)
            this.$message.error(this.hint)
            return false;
          }
        });
      },
      save(){
        this.releaseId=''
        finishTask(this.form)
          .then((data) => {
            console.log('保存==========.',data,'this.form',this.form)
            this.getCode(data)
          })
          .catch((e) => {
            this.loading=false
            console.log("error======",e)
            this.$message.error(e);
          });
      },
      /* 发布后，获取二维码，且展示*/
      async getCode(id){
        let code=''
        /*releaseChannel 1:抖音 2：快手 3：视频号*/
        if(this.form.releaseChannel==1){
         /* code = await getDyH5Code(id)
          console.log("code===============",code,code.data)
          this.updateVisible(false)
          this.$nextTick(()=>{
            this.$refs['staticDialog'].show(code)
          })*/


          var host =window.location.host;
          // var host ='oemkk.weijuyunke.com';
          let url = 'https://'+host+'/H5/aiorcode_index.html#/?codeId='+id+'&merchantId='+this.form.merchantId
          window.open(url)
          this.updateVisible(false)

        }
        if(this.form.releaseChannel==2){
          var host =window.location.host;
          // var host ='oemkk.weijuyunke.com';
          let url = 'https://'+host+'/H5/argescreen_index.html#/?releaseId='+id+'&merchantId='+this.form.merchantId
          console.log("快手url",url)
          window.open(url)
          this.updateVisible(false)

          /* const { href } = this.$router.resolve({path:`/digitalHumanManagement/ksCode`,query:{id: id }})
           window.open(href, '_blank') // _blank 打开新的页面*/
        }
        if(this.form.releaseChannel==3){
          // 数字人，视频号二维码跳转
          var host =window.location.host;
          // var host ='oemkk.weijuyunke.com';
          let url = 'https://'+host+'/H5/aiorcode_index.html#/?videoId='+id+'&merchantId='+this.form.merchantId +'&types=1'
          window.open(url)
          this.updateVisible(false)

          return
          this.releaseId=id
          this.$refs['codeDialog'].show()  // 视频号二维码展示
        }
      },

      // D音——小程序删除
      appletClear(){
        delete this.form.appUrl
        delete this.form.appTitle
        delete this.form.appId
      },
      // D音——POI删除
      poiClear(){
        delete this.form.merchantAbbreviation
        delete this.form.poiName
        delete this.form.cityName
        delete this.form.city
        delete this.provinceCity
      },
      // 视频号——公众号文章 清空
      wananchiClear(){
        this.form.sphLink = ''
        delete this.form.sphLink
      },
      /* 更新 visible */
      updateVisible(value) {
        this.seoInfo.platform=1
        this.seoInit()
        // 清空用户数据
        delete this.form.aite
        this.form.aiteNickname= ''
        // end

        //清空商家简称和城市start
        this.provinceCity=''
        this.merchantName=''
        //end

        // 发布渠道
        this.channelIndex=0
        /*
        this.userInit()*/
        this.form = {...this.defaultWhere}
        console.log("进入关闭或开启======",this.form,'this.defaultWhere}',this.defaultWhere)
        this.clear()
        this.loading=false
        this.$emit('update:visible', value);
      },
    }
  }
</script>

<style scoped lang="less">
  /*隐藏input（type=number)右边的小箭头*/
  /deep/.delInput input::-webkit-outer-spin-button,
  /deep/.delInput input::-webkit-inner-spin-button {
    -webkit-appearance: none!important;
  }
  /deep/.delInput input[type="number"]{
    -moz-appearance: textfield;
  }
  .fit-title{
    color: #333333;
    font-size: 16px;
    margin:0px 2px 20px;
  }
  .title-class,.sel-title-class{
    display: flex;
    align-items: center;
    justify-content: center;
    margin:20px 0px 15px 20px;
    width: 80px;
    padding: 5px;
    border-radius: 5px;
  }
  .title-class{
    color: #757575;
    background: #FAFAFC;
  }
  .sel-title-class{
    color: #1E6CEB;
    background: #DDF0FF;
  }
</style>
